package com.cloudkinto.common.utils.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.cloudkinto.common.common.MD5Util;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.utils.OkHttpUtils;
import com.cloudkinto.common.utils.dict.StaticDict;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.web.util.UriUtils;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URI;
import java.rmi.server.RemoteRef;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OrderCrossMallUtil {
    private static String serviceUrl = "https://crossmall.jp/";

    /**
     * SP-API 通用GET方法
     *
     * @param parametersMap
     * @return
     * @throws Exception
     */
    public static String get(String menthdName, Map<String, String> parametersMap) throws Exception {
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 10809);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder builder = getUnsafeOkHttpClient().newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .proxy(proxy)
                .retryOnConnectionFailure(false);
        String url = serviceUrl + menthdName + "?" + buildUrlParameter(parametersMap);
        Request request = new Request.Builder()
                .addHeader("Content-type", "application/json")
                .url(url)
                .get()
                .build();
        System.out.println(url);
        Response response = null;
        String body = "";
        try {
            response = builder.build().newCall(request).execute();
            body = response.body().string();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    private static String buildUrlParameter(Map<String, String> parametersMap) {
        StringBuilder data = new StringBuilder();
        if (parametersMap.get("account") == null) {
            data.append("account" + "=").append(UriUtils.encode(StaticDict.Order_CM_Account_Key.Account1.getValue(), "utf-8"));
            data.append("&");
        }
        Iterator<Map.Entry<String, String>> pairs =
                parametersMap.entrySet().iterator();
        while (pairs.hasNext()) {
            Map.Entry<String, String> pair = pairs.next();
            if (pair.getValue() != null) {
                data.append(UriUtils.encode(pair.getKey(), "utf-8")).append("=").append(UriUtils.encode(pair.getValue(), "utf-8"));
            } else {
                data.append(UriUtils.encode(pair.getKey(), "utf-8")).append("=");
            }
            if (pairs.hasNext()) {
                data.append("&");
            }
        }
        String sign = singPara(data.toString());
        data.append("&");
        data.append("signing=");
        data.append(sign);
        System.out.println("参数转换(Body)\n" + data.toString());
        return data.toString();
    }

    private static String singPara(String data) {
        MD5Util md5 = new MD5Util(SysConstant.SALT_STRING, "MD5");
        return md5.encode(data + StaticDict.Order_CM_Account_Key.Account1.getText());
    }

    //okHttp3添加信任所有证书,支持https

    public static OkHttpClient getUnsafeOkHttpClient() {
        try {
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, getX509TrustManager());

            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static X509TrustManager getX509TrustManager() {
        X509TrustManager trustManager = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            trustManager = (X509TrustManager) trustManagers[0];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return trustManager;
    }

}
